from scene import Scene, SceneTypes, SceneType
import random
import game
import dialog
import localizing
from ui import print, input, endPassage

from typing import List, Tuple

class FloorGenerator:
    @staticmethod
    def randint(a:int,b:int) -> int:
        random.seed(game.Game.I.save.data["seed"])
        return random.randint(a,b)
    
    @staticmethod
    def randList(l:list,weights:List[int]) -> Tuple:
        """
        weight 2 l
        """
        n = FloorGenerator.randint(1,sum(weights))
        for index, weight in enumerate(weights):
            if n > weight: n-= weight
            else: 
                return index,l[index]

    @staticmethod
    def floor_1(floor:"Floor") -> None:
        """
        第一层
        """

        """
        第一组为 一个战斗一个随机
        """
        fGen = FloorGenerator()
        fGen.addScene( Scene("textdungeon.game.scene.fight.spiritofknights",SceneTypes.fight) ) \
            .addScene( FloorGenerator.randList([
                Scene("textdungeon.game.scene.fight.spiritofknights",SceneTypes.fight),
                Scene("textdungeon.game.scene.fight.spiritofknights",SceneTypes.fightEmergency)
                ],[1,1])[1]) \
            .addGroup()
        
        """
        第二组为 三个不期而遇
        """
        fGen.addScene( Scene("textdungeon.game.scene.encounters.thewell",SceneTypes.encounter) ) \
            .addScene( Scene("textdungeon.game.scene.encounters.feedthem",SceneTypes.encounter) ) \
            .addScene( Scene("textdungeon.game.scene.encounters.chest",SceneTypes.encounter) ) \
            .addGroup()
        
        fGen.putIntoFloor(floor)

    def __init__(self) -> None:
        self.scenes=[]
    
    def addScene(self, scene:Scene) -> "FloorGenerator":
        if not self.scenes: self.addGroup()
        scene.pos_group = len(self.scenes)
        self.scenes[-1].append(scene)
        return self
    
    def addGroup(self) -> "FloorGenerator":
        self.scenes.append([][:])
        return self
    
    @staticmethod
    def randomSceneConnect(floor:"Floor",index:int) -> None:
        current = floor.map[index]
        last = floor.map[index-1]

        current_cnt = len(current)

        for scene in last:
            snext = []
            for i in range(current_cnt):
                if not FloorGenerator.randint(0,2): snext.append((i, current[i]))
            if not snext: 
                snext.append((0, current[0]))
            scene.setNext(snext)
    
    def putIntoFloor(self,floor:"Floor") -> None:
        for index, scene_group in enumerate(self.scenes[:-1]):
            floor.insertScenes(scene_group)
            if index > 0: # 进行连接
                self.randomSceneConnect(floor,index)

        self.scenes.clear()

class Floor:
    def __init__(self) -> None:
        self.map = []
        self.pos_group = -1
        self.pos_step = -1

    def insertScenes(self,scenes:List[Scene]) -> None:
        if len(scenes) > 3: scenes = scenes[:3]
        self.map.append(scenes)

    def choicesNextSelected(self,cm: dialog.ChoiceManager,scenes: List[Scene]) -> None:
        print( localizing.Localizer.I.get("textdungeon.game.scene.nextscene").format(len(scenes)) )
        
        for scene in scenes:
            def _func():
                self.pos_group = scene.pos_group
                self.pos_step += 1

            cm.addChoice(dialog.Choice("textdungeon.game.scene",_func,scene.print()))
        
        cm.Run()

    def choicesNext(self,cm: dialog.ChoiceManager) -> bool:
        """
        pos_step = -1 即为刚进入，任选 pos_group = 0
        否则只能选择连接的
        """
        if len(self.map) - 1 <= self.pos_step: return False

        if self.pos_step < 0: # 刚进入
            self.choicesNextSelected(cm, self.map[0])
        else: # 选可以的
            ava = [k[1] for k in self.map[self.pos_step][self.pos_group].next]
            self.choicesNextSelected(cm, ava)
        return True